/**
 * Copyright 2018-2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.action;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.jianggujin.modulelink.exception.JModuleLinkException;
import com.jianggujin.modulelink.module.JModule;
import com.jianggujin.modulelink.module.JModuleState;
import com.jianggujin.modulelink.util.JAssert;
import com.jianggujin.modulelink.util.JLogFactory;
import com.jianggujin.modulelink.util.JLogFactory.JLog;

/**
 * Action的代理
 * 
 * @author jianggujin
 *
 */
public class JActionProxyHandler implements InvocationHandler {
    private static final JLog logger = JLogFactory.getLog(JActionProxyHandler.class);
    private final JModule<?> module;
    private final Object target;
    private final String name;

    public JActionProxyHandler(JModule<?> module, Object target, String name) {
        this.module = module;
        this.target = target;
        this.name = name;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (logger.isDebugEnabled()) {
            logger.debug("invoke action method:" + method.getName() + ", declaringClass:" + method.getDeclaringClass());
        }
        JAssert.checkState(JModuleState.ACTIVED == module.getModuleState(),
                "module state is not actived. current state %s", module.getModuleState());
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try {
            JModuleContext.set(module);
            Thread.currentThread().setContextClassLoader(module.getModuleClassLoader());
            return method.invoke(target, args);
        } catch (Exception e) {
            throw new JModuleLinkException("invoke action has error, action:" + name, e);
        } finally {
            JModuleContext.clear();
            Thread.currentThread().setContextClassLoader(classLoader);
        }
    }

    protected Object getTarget() {
        return this.target;
    }
}
